package com.forlove.app.qselect.friend.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.forlove.app.ForloveApplication;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.network.ICallBack;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.NetworkUtils;
import com.forlove.app.common.utils.ParseHelper;
import com.forlove.app.common.utils.PermissionsChecker;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.utils.ViewUtils;
import com.forlove.app.manager.ContactsManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.ServerManager;
import com.forlove.app.qselect.MainActivity;
import com.forlove.app.qselect.answer.entity.AnswerEntity;
import com.forlove.app.qselect.friend.presenter.AddFriendGuidePresenter;
import com.forlove.app.qselect.friend.view.AddFriendGuideView;
import com.forlove.app.qselect.index.ui.AddFriendsActivity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * 添加好友引导页
 * Created by yjl on 2017/12/8.
 */
@RuntimePermissions
public class AddFriendGuideActivity extends BaseActivity<AddFriendGuidePresenter>
        implements AddFriendGuideView, View.OnClickListener {

    @BindView(R.id.sim_fre)
    SimpleDraweeView sim_fre;

    @BindView(R.id.text_add_other)
    TextView text_add_other;

    @BindView(R.id.bt_load_from_contacts)
    FrameLayout bt_load_from_contacts; //通讯录导入

    @BindView(R.id.text_load)
    TextView text_load;//通讯录导入

    @BindView(R.id.text_tip)
    TextView text_tip; //导入通讯录和添加好友提示

    @BindView(R.id.bt_add_other_friend)
    TextView bt_add_other_friend;//添加好友

    @BindView(R.id.progress_load)
    ContentLoadingProgressBar progress_load;

    @BindView(R.id.view_load_friend)
    LinearLayout view_load_friend; //显示加载好友界面

    @BindView(R.id.view_start_circle)
    LinearLayout view_start_circle; //显示开始圈一圈好友

    @BindView(R.id.text_add_friends_num)
    TextView text_add_friends_num;//添加完好友提示

    @BindView(R.id.bt_start_circle)
    TextView bt_start_circle;//开始圈一圈

    @BindView(R.id.text_add_more)
    TextView text_add_more; //添加更多好友

    private int contactsNum = -1;//通讯录数
    private int friendsNum = -1;//好友数
    private int loadNum = 200;//分批上传数目，不可为0
    private int mFrom = -1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_friend_guide;
    }

    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new AddFriendGuidePresenter(this);
        }

        initGif();
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            showLoadFriendView();
        } else {
            mFrom = bundle.getInt("from", -1);
            if (mFrom > 0) {
                showFromAddFriendView(bundle);
            } else {
                //没有获取到值默认显示加载好友页面
                showLoadFriendView();
            }
        }

    }

    private void showFromAddFriendView(Bundle bundle) {
        view_start_circle.setVisibility(View.VISIBLE);
        view_load_friend.setVisibility(View.GONE);
        bt_start_circle.setOnClickListener(this);
        text_add_more.setOnClickListener(this);
        if (mFrom == AddFriendsActivity.from_skip) {
            //跳过，请求答题接口获取推荐好友人数
            text_add_friends_num.setText(String.format(getString(R.string.str_show_msg), 0));
//            text_add_friends_num.setText(R.string.str_show_msg);
            text_add_friends_num.setVisibility(View.INVISIBLE);
            text_add_more.setText("自己选择投票对象");
            presenter.loadQuestionData();
        } else if (mFrom == AddFriendsActivity.from_next_step) {
            //显示选择了好友后进入页面
            if (bundle != null) {
                int num = bundle.getInt("friendnum", -1);
                if (num > 0) {
                    text_add_friends_num.setText(String.format(getString(R.string.str_has_add_friend), num));
                } else {
                    text_add_friends_num.setText(getString(R.string.str_show_msg_nofriend));
                }
                text_add_friends_num.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (mFrom == 1 || mFrom == 2) {
            toMainActivity();
            finish();
        } else {
            super.onBackPressed();
        }
    }

    private void showLoadFriendView() {
        setCanBack(false);
        view_load_friend.setVisibility(View.VISIBLE);
        view_start_circle.setVisibility(View.GONE);
        bt_load_from_contacts.setOnClickListener(this);
        bt_add_other_friend.setOnClickListener(this);
        text_add_other.setOnClickListener(this);
        initAddOther();
    }

    private void initGif() {
        DraweeController mDraweeController = Fresco.newDraweeControllerBuilder().setAutoPlayAnimations(true)
                //设置uri,加载本地的gif资源
                .setUri(Uri.parse("res://" + getPackageName() + "/" + R.mipmap.add_friend_guide))//设置uri
                .build();
        //设置Controller
        sim_fre.setController(mDraweeController);
    }

    private void initAddOther() {
        int length = text_add_other.getText().length();
        ViewUtils.customTextColor(text_add_other, Color.parseColor("#333333"), 5, length);
    }

    private long deltTime = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_load_from_contacts:
                if (System.currentTimeMillis() - deltTime < 1000) {
                    deltTime = System.currentTimeMillis();
                    return;
                }
                AddFriendGuideActivityPermissionsDispatcher.needContactsWithPermissionCheck(this);
                break;
            case R.id.bt_add_other_friend:
            case R.id.text_add_other:
            case R.id.text_add_more:
                toMainActivity(MainActivity.POSITION_FRIEND);
                finish();
                break;
            case R.id.bt_start_circle:
                //开始圈一圈
                Bundle bundle = new Bundle();
                bundle.putInt(MainActivity.Key_Comefrom, MainActivity.COME_FROM_ADD_FRIEND_GUIDE);
                toMainActivity(bundle);
                finish();
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            showLoadFriendView();
        } else {
            mFrom = bundle.getInt("from", -1);
            if (mFrom > 0) {
                showFromAddFriendView(bundle);
            } else {
                //没有获取到值默认显示加载好友页面
                showLoadFriendView();
            }
        }
    }

    /**
     * 显示添加好友按钮
     */
    private void showAddFriend() {
        //TODO 人数不足或者获取通讯录人数为0
        text_tip.setText(R.string.str_to_add_friend);
        bt_add_other_friend.setVisibility(View.VISIBLE);
        bt_load_from_contacts.setVisibility(View.GONE);
        text_add_other.setVisibility(View.INVISIBLE);
    }

    /**
     * 拒绝权限显示
     */
    private void showRefuseContacts() {
        text_tip.setText(R.string.str_contacts_fail);
        bt_add_other_friend.setVisibility(View.VISIBLE);
        bt_load_from_contacts.setVisibility(View.GONE);
        text_add_other.setVisibility(View.INVISIBLE);
        text_load.setText(R.string.str_load_from_contacts);
    }

    private void showLoadError() {
        text_add_other.setVisibility(View.VISIBLE);
        bt_add_other_friend.setVisibility(View.GONE);
        bt_load_from_contacts.setVisibility(View.VISIBLE);
        text_load.setText(R.string.str_load_from_contacts);
    }

    @NeedsPermission({Manifest.permission.READ_CONTACTS})
    void needContacts() {
        //顺利获取权限
        LogUtil.e("yjl", "needContacts");
        LoadContactsAsy loadContactsAsy = new LoadContactsAsy();
        loadContactsAsy.execute();
        loadContactsAsy.onProgressUpdate(20);
        bt_add_other_friend.setVisibility(View.GONE);
        bt_load_from_contacts.setVisibility(View.VISIBLE);
        text_add_other.setVisibility(View.INVISIBLE);
        text_load.setText(R.string.str_load_from_contacts);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AddFriendGuideActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied({Manifest.permission.READ_CONTACTS})
    void refuseContacts() {
        //拒绝授权
        LogUtil.e("yjl", "refuseContacts");
        showRefuseContacts();
    }

    @OnNeverAskAgain({Manifest.permission.READ_CONTACTS})
    void nerverAskContactsAgain() {
        //不再询问
        LogUtil.e("yjl", "neverAskContactsAgain");
//        LogUtil.e("yjl", "Contacts:" + PermissionsChecker.getContactsPermission(this));
        if (PermissionsChecker.getContactsPermission(this)) {
            LoadContactsAsy loadContactsAsy = new LoadContactsAsy();
            loadContactsAsy.execute();
            loadContactsAsy.onProgressUpdate(20);
        } else {
            showRefuseContacts();
        }
    }

    @Override
    public void updateSubjectsView(AnswerEntity answerEntity) {
        if (answerEntity != null) {
            text_add_friends_num.setVisibility(View.VISIBLE);
            text_add_friends_num.setText(String.format(getString(R.string.str_show_msg), answerEntity.recomandFriend.size()));
        }
    }

    private class LoadContactsAsy extends AsyncTask<Void, Integer, List<ContactsInfoEntity>> {
        private int total;//总人数
        private int size;//分批长度
        private int k;//当前批次

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(List<ContactsInfoEntity> contactsInfoEntities) {
            super.onPostExecute(contactsInfoEntities);
//            if (contactsNum + friendsNum < 4) {
//                //成功上传后好友人数少于4
//                showAddFriend();
//            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            //-1出错
            int percent = values[0];
            LogUtil.e("percent:" + percent);
            progress_load.setSecondaryProgress(percent);
            if (percent == 100) {
                k = 0;
                if (Build.VERSION.SDK_INT >= 24) {
                    progress_load.setProgress(percent, true);
                } else {
                    progress_load.setProgress(percent);
                }
                text_load.setText(R.string.str_load_success);
                bt_load_from_contacts.setOnClickListener(null);
                Toast.makeText(AddFriendGuideActivity.this, "导入成功!", Toast.LENGTH_SHORT).show();
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (contactsNum + friendsNum >= 4) {
                            //跳转加好友
                            text_tip.setVisibility(View.INVISIBLE);
                            Intent intent = new Intent(AddFriendGuideActivity.this, AddFriendsActivity.class);
                            startActivity(intent);
                            finish();
                        } else {
                            showAddFriend();
                        }
                    }
                }, 1000);

            } else if (percent == -1) {
                //TODO 上传出问题
                showLoadError();

            } else if (percent == -2) {
                //TODO 没有好友或者获取通讯录人数为0或者拒绝通讯录
                showAddFriend();
            } else {
                if (Build.VERSION.SDK_INT >= 24) {
                    progress_load.setProgress(percent, true);
                } else {
                    progress_load.setProgress(percent);
                }
            }
        }

        @Override
        protected synchronized List<ContactsInfoEntity> doInBackground(Void... voids) {
            final List<ContactsInfoEntity> list = ContactsManager.getContectInfo(AddFriendGuideActivity.this);
            total = list.size();
            if (total == 0) {
                publishProgress(-2);
                return list;
            }
            //分批的总批次
            int sum = (int) Math.ceil(list.size() / (double) loadNum);
            if (total > 0) {
                publishProgress(20);
                k = 0;
                size = 0;
                uploadFriend(sum, list);
                ContactsManager.saveContactsFriend(ForloveApplication.getInstance(), list);
            }
            return list;
        }

        private void uploadFriend(final int sum, final List<ContactsInfoEntity> list) {
            if (k > sum) {
                return;
            }
            int num = k + 1;
            size = 0;
            if (total > loadNum * k && NetworkUtils.instance(AddFriendGuideActivity.this).isNetworkAvailable()) {
                StringBuilder friendsNumber = new StringBuilder();
                StringBuilder nameBuilder = new StringBuilder();
                size = (num * loadNum > list.size() ? list.size() : num * loadNum);
//                        LogUtil.e("yjl", "total:" + list.size() + "sum:" + sum + "  size:" + size);
                for (int i = k * loadNum; i < size; i++) {
                    ContactsInfoEntity contactsInfoEntity = list.get(i);
                    friendsNumber.append(contactsInfoEntity.getNumber());
                    if (StringUtils.isNotEmpty(contactsInfoEntity.getName())
                            && !StringUtils.containsEmoji(contactsInfoEntity.getName())) {
                        nameBuilder.append(contactsInfoEntity.getName());
                    } else {
                        nameBuilder.append(" ");
                    }
                    if (i < size - 1) {
                        friendsNumber.append(",");
                        nameBuilder.append(",");
                    }
                }
                final Map param = new HashMap();
                param.put("list", friendsNumber.toString());
                param.put("namelist", nameBuilder.toString());
                if (sum > 1) {
                    param.put("isupdate", "1");//1是分批上传
                }
                try {
                    NetworkManager.getInstance().loadDataByPost(ServerManager.ACTION_UPLOAD_CONTACTS, param, new ICallBack() {
                        @Override
                        public void onSuccess(int statusCode, String result) {
                            LogUtil.e("上传通讯录:" + result);
                            //上传成功
                            synchronized (this) {
                                float per = ((float) size / total);
                                int percent = (int) Math.ceil(per * 80) + 20;
                                LogUtil.e("yjl", "percent:" + percent);
                                publishProgress(percent);
                                if (StringUtils.isNotEmpty(result)) {
                                    contactsNum = ParseHelper.getInteger(result, "data.concats");
                                    friendsNum = ParseHelper.getInteger(result, "data.friends");
                                }
                                k++;
                                uploadFriend(sum, list);
                            }
                        }

                        @Override
                        public void onFail(int statusCode, String result) {
                            LogUtil.e("上传通讯录:" + result);
                            publishProgress(-1);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
